package com.xindaoapp.henghua.asset;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.library.utils.IRequest;
import com.xindaoapp.henghua.R;
import com.xindaoapp.henghua.activity.DeviceEngineerActivity.PASTETYPE;
import com.xindaoapp.henghua.activity.LabelDetailsActivity;
import com.xindaoapp.henghua.application.XinDaoApplication;
import com.xindaoapp.henghua.entry.PropertyGatherInfo;
import com.xindaoapp.henghua.entry.PropertyLabelInfo;
import com.xindaoapp.henghua.entry.ScanData;
import com.xindaoapp.henghua.protocol.HttpManager;
import com.xindaoapp.henghua.utils.MoccaPreferences;
import com.xindaoapp.henghua.utils.XinDaoBaseAdapter;
import com.xindaoapp.henghua.zbar.CameraTestActivity;

public  class DeviceWindow {
	private View view;
	private PullToRefreshListView mPullToRefreshListView;
	/** 全部的设备,过滤缓存 */
	private List<PropertyGatherInfo> list;
	private DeviceDataAdapter adapter;
	private final int tabType;
	private final Context mContext;
	private final ILoadDatas iLoadDatas;

	public DeviceWindow(Context context, int tabType, ILoadDatas iLoadDatas) {
		this.tabType = tabType;
		mContext = context;
		this.iLoadDatas = iLoadDatas;
	}

	public View getView() {
		if (null == view) {
			initViews();
		}
		return view;
	}

	public int getDataSize() {
		return list != null ? list.size() : 0;
	}

	private void initViews() {
		view = LayoutInflater.from(mContext).inflate(R.layout.item_device_viewpager, null);
		mPullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);
		adapter = new DeviceDataAdapter(mContext, new ArrayList<PropertyGatherInfo>(),
				R.layout.item_device_list_item_child);
		mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
		mPullToRefreshListView.setAdapter(adapter);
		mPullToRefreshListView.setOnRefreshListener(mOnRefreshListener);
		mPullToRefreshListView.setOnItemClickListener(mOnItemClickListener);
	}

	/**
	 * 是否有未提交的标签
	 */
	private boolean isHaveUnSubmitLabel() {
		if (XinDaoApplication.get().getDBHelper().getUnSubmitLabels().size() > 0) {
			return true;
		}
		return false;
	}

	Handler h = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				if (mPullToRefreshListView != null) {
					mPullToRefreshListView.onRefreshComplete();
				}
				break;

			default:
				break;
			}
		};
	};

	private final OnRefreshListener<ListView> mOnRefreshListener = new OnRefreshListener<ListView>() {

		@Override
		public void onRefresh(PullToRefreshBase<ListView> refreshView) {
			if (isHaveUnSubmitLabel()) {

				LoadingDialog mLoadingDialog = new LoadingDialog(mContext, R.style.Doading_Dialog);
				mLoadingDialog.setCanceledOnTouchOutside(true);
				mLoadingDialog.setImageView(R.drawable.failed);
				mLoadingDialog.show();
				h.sendEmptyMessageDelayed(0, 1000);
				return;
			}
			new HttpManager(MoccaPreferences.PROPERTYDATASTIME.get(),
					MoccaPreferences.TRANSPORTDATASTIME.get(), MoccaPreferences.SUPERVISIONTIME.get(),
					MoccaPreferences.SCANDATASTIME.get(), MoccaPreferences.PROPERTYWITHLABELDATASTIME.get(),
					MoccaPreferences.TAGSTIME.get(), MoccaPreferences.ARRIVEDATASTIME.get(),
					XinDaoApplication.get().getUserInfo().project_id)
					.getPropertyGatherInfos(new IRequest<List<PropertyGatherInfo>>() {

						@Override
						public void request(List<PropertyGatherInfo> t) {
							mPullToRefreshListView.onRefreshComplete();
							if (null != t) {
								if (t.size() > 0) {
									iLoadDatas.reloadHomePage(t);
								}
							} else {
								Toast.makeText(mContext, "加载失败", Toast.LENGTH_LONG).show();
							}
						}
					});
		}
	};

	private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			Intent intent = new Intent(mContext, LabelDetailsActivity.class);
			// 获取设备相关所有信息
			PropertyGatherInfo info = (PropertyGatherInfo) parent.getItemAtPosition(position);
			Bundle mBundle = new Bundle();
			mBundle.putSerializable("info", info);
			intent.putExtras(mBundle);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
		}
	};

	/**
	 * 通过字符串过滤
	 */
	public void textChanged(String text) {
		if (null == list) {
			return;
		}
		List<PropertyGatherInfo> temp = new ArrayList<PropertyGatherInfo>();
		for (int i = 0; i < list.size(); i++) {
			PropertyGatherInfo info = list.get(i);
			if (info.name.indexOf(text) >= 0 || info.model.indexOf(text) >= 0
					|| info.factory_name.indexOf(text) >= 0) {
				temp.add(info);
			}
		}
		resetAdatper(temp);
	}

	private void resetAdatper(List<PropertyGatherInfo> list) {
		adapter.resetData(list);
		adapter.notifyDataSetChanged();
	}

	/**
	 * 重新刷新界面
	 */
	public void reload(List<PropertyGatherInfo> list) {
		if (adapter == null) {
			return;
		}
		this.list = list;
		if (tabType == PASTETYPE.UNPASTED.ordinal()) {
			// 获取未贴标签的列表
			resetAdatper(list);
		} else if (tabType == PASTETYPE.ALL.ordinal()) {
			resetAdatper(list);
		} else if (tabType == PASTETYPE.PASTED.ordinal()) {
			// 获取已贴标签的列表
			Collections.sort(list, new SortLabe());
			System.out.println("已贴标签倒序排列");
			for (int i = 0; i < list.size(); i++) {
				System.out.println("TIME ==== " + getLastTime(list.get(i).propertyLabelInfos));
			}
			resetAdatper(list);
		}
	}

	public void refursh() {
		List<PropertyGatherInfo> list = XinDaoApplication.get().getUpdateDataChanged()
				.getPropertyGatherInfos();
		iLoadDatas.reloadHomePage(list);
		// 将1、3页面也进行初始化
		iLoadDatas.refresh(list);
	}

	/**
	 * 对数据进行排序,倒序
	 * @param list
	 */
	class SortLabe implements Comparator<PropertyGatherInfo> {
		@Override
		public int compare(PropertyGatherInfo rhs, PropertyGatherInfo lhs) {
			return getLastTime(lhs.propertyLabelInfos).compareTo(getLastTime(rhs.propertyLabelInfos));
		}
	}

	String getLastTime(List<PropertyLabelInfo> propertyLabelInfos) {
		Collections.sort(propertyLabelInfos, new ScanDataComparatorAsc());
		return propertyLabelInfos.get(0).create_time;
	}

	/**
	 * 对时间排序，倒序
	 */
	class ScanDataComparatorAsc implements Comparator<PropertyLabelInfo> {
		@Override
		public int compare(PropertyLabelInfo sd2, PropertyLabelInfo sd1) {
			return sd1.create_time.compareTo(sd2.create_time);
		}

	}

	
	
	/**
	 * 开始加载网络数据
	 * @param iRequest
	 */
	private void startLoadThread(final IRequest<List<PropertyGatherInfo>> iRequest){
	new HttpManager(XinDaoApplication.get().getUserInfo().project_id)
	.getPropertyGatherInfos(new IRequest<List<PropertyGatherInfo>>() {

		@Override
		public void request(List<PropertyGatherInfo> t) {
			mPullToRefreshListView.onRefreshComplete();
			if (null != t) {
				if (null != iRequest) {
					iRequest.request(t);
				}
			} else {
				List<PropertyGatherInfo> list = XinDaoApplication.get().getDBHelper()
						.getPropertyGatherInfos();
				XinDaoApplication.get().getUpdateDataChanged().setPropertyGatherInfos(list);
				mPullToRefreshListView.onRefreshComplete();
				iLoadDatas.reloadHomePage(list);
				// 将1、3页面也进行初始化
				iLoadDatas.refresh(list);
//				Toast.makeText(mContext, "加载失败", Toast.LENGTH_LONG).show();
			}
		}
	});
}

	/**
	 * 初始化标签
	 */
	private void initTags() {
		// 初始化标签
		if (!TextUtils.isEmpty(MoccaPreferences.TAGS.get())) {
			XinDaoApplication.get().getUpdateDataChanged()
					.setTagsInfos(XinDaoApplication.get().getDBHelper().getTagsInfos());
		}
	}

	/**
	 * 获取设备信息，从数据库读取数据，如果为空，则从服务器获取数据
	 */
	public void initPropertyInfos() {
		initTags();

		/*List<PropertyGatherInfo> list = XinDaoApplication.get().getDBHelper().getPropertyGatherInfos();
		XinDaoApplication.get().getUpdateDataChanged().setPropertyGatherInfos(list);*/

//		if (list.size() == 0) {
		// 服务器获取数据
		startLoadThread(new IRequest<List<PropertyGatherInfo>>() {

			@Override
			public void request(List<PropertyGatherInfo> t) {
				// 清空所有表
				XinDaoApplication.get().getDBHelper().clearAllTable();

				// 保存数据到数据库
				for (PropertyGatherInfo info : t) {
					XinDaoApplication.get().getDBHelper().insertPropertyGatherInfo(info);
				}
				iLoadDatas.reloadHomePage(t);
			}
		});
		/*} else {
			mPullToRefreshListView.onRefreshComplete();
			iLoadDatas.reloadHomePage(list);
			// 将1、3页面也进行初始化
			iLoadDatas.refresh(list);
		}*/
	}

	/**
	 * 设备列表适配器
	 * @author chenghao
	 *
	 */
	class DeviceDataAdapter extends XinDaoBaseAdapter<PropertyGatherInfo> {

		public DeviceDataAdapter(Context context, List<PropertyGatherInfo> mList, int resId) {
			super(context, mList, resId);
		}

		@Override
		public View getView(int position, View contentView, ViewGroup parent, final PropertyGatherInfo t) {
			ViewHolder holder = (ViewHolder) contentView.getTag();
			if (holder == null) {
				holder = new ViewHolder();
				holder.haveImage = (ImageView) contentView.findViewById(R.id.have_image);
				holder.serialNumber = (TextView) contentView.findViewById(R.id.serial_number);
				holder.deviceNumber = (TextView) contentView.findViewById(R.id.device_number);
				holder.name = (TextView) contentView.findViewById(R.id.name);
				holder.model_number = (TextView) contentView.findViewById(R.id.model_number);
				holder.device_company = (TextView) contentView.findViewById(R.id.device_company);
				holder.label_number = (TextView) contentView.findViewById(R.id.label_number);
				holder.label = (ImageView) contentView.findViewById(R.id.label);
				contentView.setTag(holder);
			}

			if (isHaveImage(t)) {
				holder.haveImage.setVisibility(View.VISIBLE);
			} else {
				holder.haveImage.setVisibility(View.GONE);
			}
			holder.serialNumber.setText(String.valueOf(position + 1));
			holder.deviceNumber.setText(t.code);
			holder.name.setText(t.name);
			holder.model_number.setText(t.model);
			holder.device_company.setText(t.factory_name);
			if (null != t.propertyLabelInfos) {
				holder.label_number.setText(String.valueOf(t.propertyLabelInfos.size()));
			} else {
				holder.label_number.setText(String.valueOf(0));
			}
			// holder.label.setImageResource(R.drawable.label_normal);
			holder.label.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(mContext, CameraTestActivity.class);
//					Intent intent = new Intent(getBaseContext(), CaptureActivity.class);
					Bundle mBundle = new Bundle();
					mBundle.putSerializable("info", t);
					intent.putExtras(mBundle);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//					intent.putExtra("scanCode", "F58DB107568FD685E040A8C078011E14");
					mContext.startActivity(intent);
				}
			});
			if (position % 2 == 0) {
				contentView.setBackgroundResource(R.drawable.device_one_item);
			} else {
				contentView.setBackgroundResource(R.drawable.device_two_item);
			}

			return contentView;
		}

		class ViewHolder {
			/** 是否有照片 */
			ImageView haveImage;
			TextView serialNumber;
			TextView deviceNumber;
			TextView name;
			TextView model_number;
			TextView device_company;
			TextView label_number;
			ImageView label;
		}

		private boolean isHaveImage(PropertyGatherInfo t) {
			if (null != t.scanDatas) {
				for (ScanData scanData : t.scanDatas) {
					if (null != scanData.photos && null != scanData.photos.breviaryphotos
							&& scanData.photos.breviaryphotos.size() > 0) {
						return true;
					}
				}
			}
			return false;
		}

	}
}
